<template>
  <div>
    <el-dialog v-model="dialogFormVisible" :title="title" width="800" destroy-on-close :close-on-click-modal="closeOnClickModal">
      <el-form ref="formRef" :model="form" :rules="rules">
        <el-form-item label="规格名称" prop="specName" :label-width="formLabelWidth">
          <el-input v-model="form.specName" autocomplete="off" placeholder="请输入规格名称" clearable />
        </el-form-item>
      </el-form>
      <div>
        <div v-if="tagShow" style="margin-bottom: 15px;" v-for="(item, index) in specDatas" :key="index">
          <div style="margin-bottom: 10px;">
            <span>{{ item.specKey }}</span>
            <el-icon @click="closeTag(item.specDetailId, index)"><CircleCloseFilled /></el-icon>
          </div>
          <div class="flex gap-2">
            <el-tag
              v-for="tag in item.specValues"
              :key="tag"
              closable
              :disable-transitions="false"
              @close="handleClose(tag, index)"
            >
              {{ tag }}
            </el-tag>
            <el-input
              v-if="index === inputShow"
              ref="InputRef"
              v-model="inputValue"
              class="w-20"
              size="small"
              autofocus
              @keyup.enter="handleInputConfirm"
              @blur="handleInputConfirm"
            />
            <el-button v-else class="button-new-tag" size="small" @click="showInput(index)">
              + 添加
            </el-button>
          </div>
        </div>
        <el-button v-if="formBtnShow" type="primary" @click="createNewSpec">
          添加新规格
        </el-button>
        <el-form v-if="formShow" :inline="true" :model="formInline" class="demo-form-inline">
          <el-form-item label="规格" prop="specKey" :label-width="formLabelWidth">
            <el-input v-model="formInline.specKey" placeholder="请输入规格" clearable />
          </el-form-item>
          <el-form-item label="规格值" prop="specValue" :label-width="formLabelWidth">
            <el-input v-model="formInline.specValue" placeholder="请输入规格值" clearable />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="setSpecDatas">确定</el-button>
            <el-button @click="onCancel">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSaveOrUpdate">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
  import { reactive, ref } from 'vue'
  import { ElMessageBox } from 'element-plus'
  import { saveOrUpdate, getSpecInfo, removeSpecDetail } from '~/api/product/spec'
  import { showMessage } from '~/utils/my-notification'

  const emit = defineEmits(['refreshDataList'])

  const formRef = ref(null)
  const dialogFormVisible = ref(false)
  const formLabelWidth = '80px'
  const title = ref('新建用户')
  const closeOnClickModal = ref(false)
  const formShow = ref(false) // 规格表单是否显示
  const formBtnShow = ref(true) // 添加规格按钮是否显示
  const tagShow = ref(false) // tag标签是否显示
  const inputValue = ref('')
  const InputRef = ref()
  const specDatas = ref([]) // 规格列表数据
  const tagIndex = ref(0) // 当前点击tag标签的下标
  const inputShow = ref('') // tag标签中的input框是否显示

  function handleClose(tag, index) {
    specDatas.value[index].specValues.splice(specDatas.value[index].specValues.indexOf(tag), 1)
  }
  function showInput(index) {
    tagIndex.value = index
    inputShow.value = index
  }
  function handleInputConfirm() {
    if (inputValue.value) {
      specDatas.value[tagIndex.value].specValues.push(inputValue.value)
    }
    inputShow.value = ''
    inputValue.value = ''
  }
  // 关闭tag
  function closeTag(specDetailId, index) {
    if(specDetailId) {
      ElMessageBox.confirm(`确定执行删除操作,确定将删除数据库中的数据?`, '提示',{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        closeOnClickModal: false
      }).then(() => {
        removeSpecDetail(specDetailId).then(res => {
          if(res && res.data.code === 200) {
            showMessage('删除成功!')
            specDatas.value.splice(index, 1)
          } else {
            showMessage('删除失败!', 'error')
          }
        }).catch(err => {
          showMessage('删除失败!', 'error')
        })
      }).catch(() => {

      })
    } else {
      specDatas.value.splice(index, 1)
    }
  }

  const form = reactive({
    id: 0,
    specName: ''
  })
  const formInline = reactive({
    specKey: '',
    specValue: ''
  })
  const rules = {
    specName: [
      { required: true, message: '规格名称不能为空!', trigger: 'blur' },
    ]
  }

  function init(id) {
    dialogFormVisible.value = true
    formShow.value = false
    formBtnShow.value = true
    tagShow.value = false
    form.id = 0
    form.specName = ''
    specDatas.value = []
    if(id) {
      formShow.value = false
      formBtnShow.value = true
      tagShow.value = true
      // 查询详情
      getSpecInfo(id).then(res => {
        if(res && res.data.code === 200) {
          const data = res.data.data
          form.id = data.id
          form.specName = data.specName
          const specValue = data.specValue
          let datas = []
          specValue.forEach((item, index) => {
            let d = {
              specDetailId: item.specDetailId,
              specKey: item.specKey,
              specValues: item.specValues
            }
            datas.push(d)
          });
          specDatas.value = datas
        }
      })
    }
  }
  // 保存或修改操作点击事件
  function handleSaveOrUpdate() {
    formRef.value.validate((valid) => {
      if(!valid) {
        return false
      }
      ElMessageBox.confirm(`确定进行保存操作?`, '提示',{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        closeOnClickModal: false
      }).then(() => {
        var formData = {
          id: form.id,
          specName: form.specName,
          specValue: specDatas.value
        }
        saveOrUpdate(formData).then(res => {
          if(res && res.data.code === 200) {
            dialogFormVisible.value = false
            emit('refreshDataList')
          } else {
            showMessage(res.data.message, 'error')
          }
        })
      }).catch(err => {
        console.log(err)
      })
    })
  }
  // 为tag标签赋值
  function setSpecDatas() {
    formShow.value = false
    formBtnShow.value = true
    tagShow.value = true
    specDatas.value.push({
      specKey: formInline.specKey,
      specValues: [formInline.specValue]
    })
    formInline.specKey = ''
    formInline.specValue = ''
  }
  // 取消按钮点击事件
  function onCancel() {
    formShow.value = false
    formBtnShow.value = true
    tagShow.value = false
  }
  // 添加新规格
  function createNewSpec() {
    formShow.value = true
    formBtnShow.value = false
  }

  // 将方法暴露给父组件
  defineExpose({
    init
  })
</script>
<style>

</style>